import tkinter as tk
from tkinter import messagebox
import subprocess
import sqlite3
root = tk.Tk()
root.title("Login")

def login():
    # 获取用户名和密码
    username = username_entry.get()
    password = password_entry.get()

    # 连接到SQLite数据库并执行认证
    if authenticate(username, password):
        print("认证成功！")
        # 在这里执行认证成功后的操作，比如打开新窗口或加载其他内容

        subprocess.call(['python', 'music.py'])  # 启动另一个Python文件 
        root.destroy()  # 关闭当前页面

    else:
        print("认证失败！用户名或密码不正确。")
        messagebox.showinfo("错误", "用户名或密码不正确")

#通过数据库判断账号密码是否正确
def authenticate(username, password):
    # 连接到SQLite数据库
    conn = sqlite3.connect('music_app.db')
    cursor = conn.cursor()

    # 执行SQL查询，检查用户名和密码是否匹配
    cursor.execute("SELECT * FROM users WHERE username = ? AND password = ?", (username, password))
    user = cursor.fetchone()

    # 关闭连接
    conn.close()

    # 如果查询结果不为空，则认证成功
    if user:
        return True
    else:
        return False
# 设置窗口大小和位置
root.geometry("300x400")
root.resizable(False, False)
# 设置背景图片
bg_image = tk.PhotoImage(file="login.gif")
background_label = tk.Label(root, image=bg_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)
#欢迎登陆字样
username_label = tk.Label(root, text="欢迎登陆听歌系统:", font=("Helvetica", 16))
username_label.place(relx=0.5, rely=0.25, anchor="center")

username_label = tk.Label(root, text="Username:", bg="white")
username_label.place(relx=0.5, rely=0.34, anchor="center")
username_entry = tk.Entry(root, width=30)
username_entry.place(relx=0.5, rely=0.40, anchor="center")

password_label = tk.Label(root, text="Password:", bg="white")
password_label.place(relx=0.5, rely=0.47, anchor="center")
password_entry = tk.Entry(root, width=30, show="*")
password_entry.place(relx=0.5, rely=0.53, anchor="center")

# 创建登录按钮
login_button = tk.Button(root, text="登录", width=10, command=login, bg="#4CAF50", fg="white")
login_button.place(relx=0.5, rely=0.63, anchor="center")
#注册页面跳转函数
def jump_enroll():
    subprocess.call(['python', 'enroll.py'])

# register_button = tk.Button(root, text="注册", width=10, command=enroll, bg="#2196F3", fg="white")
register_button = tk.Button(root, text="注册", width=10, command=jump_enroll, bg="#2196F3", fg="white")
register_button.place(relx=0.5, rely=0.75, anchor="center")



root.mainloop()
